package com.my.micro.service.order.api;

import com.my.micro.service.order.domain.Goods;
import com.my.micro.service.order.domain.Order;
import com.my.micro.service.order.feign.GoodsApi;
import com.my.micro.service.order.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 控制层
 *
 * @author Zijian Liao
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/get")
    public String get(){
        // 旧方式：restTemplate.getForObject("http://127.0.0.1:8081/goods/get", String.class)
        long start = System.currentTimeMillis();
        try{
            return restTemplate.getForObject("http://my-goods/goods/get", String.class);
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }finally {
            System.out.println(System.currentTimeMillis() - start);
        }
    }

    @Resource
    private GoodsApi goodsApi;

    @GetMapping("/get-goods")
    public Goods getGoods(){
        return goodsApi.getGoods();
    }

    @GetMapping("/list")
    public List<Goods> goods(){
        return goodsApi.list();
    }

    @GetMapping
    public String saveGoods(){
        goodsApi.save(new Goods().setName("banana").setNumber(1).setPrice(1.1));
        return "ok";
    }

    @GetMapping("/post")
    public String post(){
        // 旧方式：restTemplate.getForObject("http://127.0.0.1:8081/goods/get", String.class)
        long start = System.currentTimeMillis();
        try{
            return restTemplate.postForObject("http://my-goods/goods/post", null, String.class);
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }finally {
            System.out.println(System.currentTimeMillis() - start);
        }
    }

    @GetMapping("/integral")
    public String integral(){
        String url = "http://my-integral/integral/remain";
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/order")
    public String order(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("用户下了个单");
        return "this is product asking";
    }



}
